﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CodeStash.Common.DataAccess.UnitOfWork;
using System.ComponentModel.Composition;
using System.Data.Entity;
using System.Linq.Expressions;

namespace CodeStash.Common.DataAccess.Repository
{
    public class Repository<T> : IRepository<T> where T : class
    {
        protected IUnitOfWork _context;

        public void EnrolInUnitOfWork(IUnitOfWork unitOfWork)
        {
            this._context = unitOfWork;
        }


        public int Count
        {
            get { return _context.Get<T>().Count(); }
        }
        public void Add(T item)
        {
            _context.Add(item);
        }
        public bool Contains(T item)
        {
            return _context.Get<T>().FirstOrDefault(t => t == item) != null;
        }
        public void Remove(T item)
        {
            _context.Remove(item);
        }
        public IQueryable<T> FindAll()
        {
            return _context.Get<T>();
        }

        public IQueryable<T> FindAll(Func<DbSet<T>, IQueryable<T>> lazySetupAction)
        {

            DbSet<T> set = ((DbSet<T>)_context.Get<T>());
            return lazySetupAction(set);
        }


        public IQueryable<T> FindAll(string lazyIncludeStrings)
        {
            DbSet<T> set = ((DbSet<T>)_context.Get<T>());
            return set.Include(lazyIncludeStrings).AsQueryable<T>();
        }



        public IQueryable<T> FindBy(Func<T, bool> predicate)
        {
            return _context.Get<T>().Where(predicate).AsQueryable<T>();
        }

        public IQueryable<T> FindByExp(Expression<Func<T, bool>> predicate)
        {
            return _context.Get<T>().Where(predicate).AsQueryable<T>();
        }

        public IQueryable<T> FindBy(Func<T, bool> predicate, string lazyIncludeString)
        {
            DbSet<T> set = (DbSet<T>)_context.Get<T>();
            return set.Include(lazyIncludeString).Where(predicate).AsQueryable<T>();
        }

        public IQueryable<T> FindByExp(Expression<Func<T, bool>> predicate, string lazyIncludeString)
        {
            return _context.Get<T>().Where(predicate).AsQueryable<T>();
        }
    }
}